#include "syscall.h"

void itoa(char buffer[], int size, int value){
	int i, j, temp;
	int count = 0; /*count the length of input value*/
	int isNegative = 0; /* if not negative -> 0, negative -> -1 */

	/*first, initialize the char array to null*/
	for ( i = 0; i < size; i++){
		buffer[i] = '\0';
	}

	/*check to see the value is positive or negative*/
	if(value < 0){
		value = -value;
		isNegative = -1;
		count++;
	}

	/*count the space needed to use in buffer for the value*/
	temp = value;
	do{
		count++;
		temp/=10;
	}while(temp > 0);

	/*if value is negative, put the negative sign in the first space of the array*/
	if(isNegative == -1){
		buffer[0] = '-';
	}

	/*put each digit into array in right order*/
	j = count - 1;
	do{
		buffer[j--] = value % 10 + '0';
		value /= 10;

	}while(value > 0);	
	
}

void printf(char buffer[], int values[]) {
	int i = 0;
	int j = 0;
	int k;
	int m = 0;
	char intBuf[10];
	char charBuf[200];
	int valueIndex = 0;

	/*Initialize the char array that we use to store char from buffer[]*/
	for ( k = 0; k < 200; k++){
		charBuf[k] = '\0';
	}

	/*Copy the buffer[] into a new char array named charBuf[]*/
	while(buffer[i] != '\0'){
		if(buffer[i] == '%' && buffer[i+1] == 'd') {
			itoa(intBuf, 10, values[valueIndex]);

			j = 0;
			while(intBuf[j] != '\0'){ 				
				charBuf[m+j] = intBuf[j];
				j++;
			}

			i = i+2;
			m = m+j;
			valueIndex++;
		} else {

			charBuf[m] = buffer[i];		
			i++;
			m++;
		}
	}
	Write(charBuf, 200, ConsoleOutput);
}

printString(char buffer[]){
	int i = 0;
	int k;
	char charBuf[200];

	/*Initialize the char array that we use to store char from buffer[]*/
	for ( k = 0; k < 200; k++){
		charBuf[k] = '\0';
	}

	while(buffer[i] != '\0'){
		charBuf[i] = buffer[i];
		i++;
	}
	
	Write(charBuf, 200, ConsoleOutput);
}
